class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution(object):
    def addTwoNumbers(self, l1, l2):
        dummy = ListNode(0)  # 创建哑节点作为返回链表的头节点
        current = dummy  # 当前节点指针
        carry = 0  # 进位值

        while l1 or l2 or carry:  # 只要还有节点或进位未处理完
            # 获取当前节点的值，如果节点为空则为0
            val1 = l1.val if l1 else 0
            val2 = l2.val if l2 else 0

            # 计算当前位的和以及进位
            total = val1 + val2 + carry
            carry = total // 10  # 计算进位
            digit = total % 10  # 计算当前位的值

            # 创建新节点并连接到结果链表
            current.next = ListNode(digit)
            current = current.next

            # 移动指针到下一个节点
            if l1: l1 = l1.next
            if l2: l2 = l2.next

        return dummy.next  # 返回哑节点的下一个节点，即真正的头节点

# 辅助函数：将列表转换为链表
def list_to_linkedlist(lst):
    dummy = ListNode(0)
    current = dummy
    for val in lst:
        current.next = ListNode(val)
        current = current.next
    return dummy.next

# 辅助函数：将链表转换为列表（用于验证结果）
def linkedlist_to_list(head):
    result = []
    current = head
    while current:
        result.append(current.val)
        current = current.next
    return result

# 测试示例
l1 = list_to_linkedlist([2, 4, 3])  # 构建链表 2->4->3
l2 = list_to_linkedlist([5, 6, 4])  # 构建链表 5->6->4

solution = Solution()
result = solution.addTwoNumbers(l1, l2)  # 正确调用

print(linkedlist_to_list(result))  # 输出: [7, 0, 8]